/**
 *行业管理
 */
var pageCurr;
var form;

$(function() {
    layui.use(["tree", "util","table"], function(){
        var table = layui.table;
        form = layui.form;
        var tree = layui.tree
        ,layer = layui.layer
        ,util = layui.util


        $.ajax({
            type: "post",
            data: {pageNum:1,pageSize:10000},
            url: '/industry/industryList',
            success: function (dataResource) {
              var  data = convert(dataResource.list);

                //开启节点操作图标
                tree.render({
                    elem: '#zTree'
                    , data: data
                    , edit: ['add', 'update', 'del'] //操作节点的图标
                    , click: function (obj) {
                        //点击节点时触发
                        var elem = obj.elem; //得到当前节点元素

                        layer.msg(JSON.stringify(obj.data));

                    }, operate: function (obj) {
                        var type = obj.type; //得到操作类型：add、edit、del
                        var data = obj.data; //得到当前节点的数据
                        var elem = obj.elem; //得到当前节点元素
                        var url = "";
                        //Ajax 操作
                        var id = data.id; //得到节点索引
                        if (type === 'add') { //增加节点
                            return;
                        } else if (type === 'update') { //修改节点
                            url = "/industry/setIndustry"
                        } else if (type === 'del') { //删除节点
                            url = "/industry/del";
                            if (elem.parent().parent().attr("data-id") == "undefined") {
                                layer.alert("这个节点不能删除！");
                                return;
                            }
                        }
                        ;
                        var pid = elem.parent().parent().attr("data-id");//父节点id
                        var title = data.title;
                        var industryId = elem.attr("data-id");
                        if (industryId == "undefined") {
                            industryId = null;
                        }
                        //将数据提交到服务器
                        $.ajax({
                            type: "post",
                            data: {industryId: industryId, pid: pid, industryName: title},
                            url: url,
                            success: function (data) {
                                if (data.code == 1) {
                                    if (data.industryId != "" && data.industryId != null) {
                                        elem.attr("data-id", data.industryId);
                                    }
                                    layer.alert(data.msg, function () {
                                        layer.closeAll();
                                        //load(obj);
                                    });
                                } else {
                                    layer.alert(data.msg);
                                }
                            },
                            error: function () {
                                layer.alert("操作请求错误，请您稍后再试", function () {
                                    layer.closeAll();
                                    load(obj);
                                });
                            }
                        });
                    }
                });


            }
    })


        tableIns=table.render({
            id:'id',
            elem: '#industryList',
            url:'/industry/industryList',
            method: 'post', //默认：get请求
            cellMinWidth: 80,
            page: true,
            height: 'full-'+270,
            request: {
                pageName: 'pageNum', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response:{
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 200, //成功的状态码，默认：0
                countName: 'totals', //数据总数的字段名称，默认：count
                dataName: 'list' //数据列表的字段名称，默认：data
            },
            cols: [[
                {field:'industryId',title:'行业编号',align:'center'}
                ,{field:'industryName',title:'行业名称',align:'center'}
                ,{field:'createTime', title:'创建时间',align:'center',templet:'<div>{{DateUtils.formatDate(d.createTime)}}</div>'}
                ,{field:'userName', title:'创建人',align:'center'/*,width:"10%"*/}
                ,{field:'userId',hide:'true',width:"7%"}
                ,{fixed:'right',title:'操作',align:'left',width:"7%"/*toolbar:'#optBar',width:"25%"*/,
                     templet:function (d) {
                         if(d.pids !=null&&d.pids.split(",").length==3){
                             return $("#optBar").html();
                         }else {
                             return "";
                         }
                     }
                  }
            ]],
            done: function(res, curr, count){
                var dataResource = res.list;
                pageCurr=curr;
            }
        });





        //监听工具条
        table.on('tool(industryTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                //删除
                del(data,data.industryId);
            } else if(obj.event === 'edit'){
                //编辑
                edit(data);
            } else if(obj.event ==='jump'){
                delete data.updateTime;
                delete data.createTime;
               jump(data);
            }
        });
        //监听提交
        form.on('submit(industrySubmit)', function(data){
            formSubmit(data);
            return false;
        });
        form.on('submit(searchSubmit)', function(data){
            //重新加载table
            load(data);
            return false;
        });

    });

});

//提交表单
function formSubmit(obj){
    $.ajax({
        type: "post",
        data: $("#industryForm").serialize(),
        url: "/industry/setIndustry",
        success: function (data) {
            if (data.code == 1) {
                layer.alert(data.msg,function(){
                    layer.closeAll();
                    load(obj);
                });
            } else {
                layer.alert(data.msg);
            }
        },
        error: function () {
            layer.alert("操作请求错误，请您稍后再试",function(){
                layer.closeAll();
                load(obj);
            });
        }
    });
}
//新增
function add() {
    edit(null,"新增");
}
//删除
function del(obj,id) {
    if(null!=id){
        layer.confirm('您确定要删除吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/industry/del",{"id":id},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}
//打开编辑框
function edit(data,title){
    var parentId = null;
    if(data == null){
        $("#industryName").val("");
    }else{
        //回显数据
        $("#industryName").val(data.industryName);
        $("#industryId").val(data.industryId);
        $("#userId").val(data.userId);
        $("#createTime").val(data.createTime);

    }
    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);


    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['550px'],
        content:$('#setIndustry'),
        end:function(){
            cleanIndustry();
        }
    });
}

function cleanIndustry() {
    $("#industryName").val("");
}

//重新加载table
function load(obj){
    tableIns.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
}
function jump(data) {
    var form = $("<form method='post'></form>");
    var input;
    form.attr({"action":"/report/reportManage"});
    $.each(data,function (key,value) {
        input = $("<input type='hidden'>");
        input.attr({"name":key});
        input.val(value);

        form.append(input);
    });
    $(document.body).append(form);
    form.submit();
}

function exists(rows, parentId){
    for(var i=0; i<rows.length; i++){
        if (rows[i].industryId == parentId) {
            return true;
        }
    }
    return false;
}

function convert(rows){
    var nodes = [];
    //取到第一级菜单
    for(var i=0; i<rows.length; i++){
        var row = rows[i];
        if (!exists(rows, row.pid)){
            nodes.push({
                id:row.industryId+"",
                title:row.industryName,
                pids:row.pids
            });
        }
    }

    var toDo = [];
    for(var i=0; i<nodes.length; i++){
        toDo.push(nodes[i]);
    }
    while(toDo.length){
        var node = toDo.shift();    // the parent node
        //取得子菜单
        for(var i=0; i<rows.length; i++){
            var row = rows[i];
            if (row.pid == node.id){
                var child = {id:row.industryId+"",title:row.industryName};
                if (node.children){
                    node.children.push(child);
                } else {
                    node.children = [child];
                }
                if (row.pids !=null&& row.pids.split(",").length <3){
                    node.spread = true;
                }
                toDo.push(child);
            }
        }
    }
    return nodes;
}